const Response = require("../../class/Response");
const LocalEvent = require("../../class/LocalEvent");

WSS.onEvent("PlayerMessage", async (thisClient, req, res)=>{
    // 这里只接收来自MC客户端的聊天消息，来自BDS的聊天消息在BDS路由部分, 为什么分开？MC客户端的聊天需要回显，BDS的聊天则不需要
    if (thisClient.userType!='player'){return;}

    let sendmsg = req.body.message;
    const sender = req.body.sender;
    const type = req.body.type;
    const chatHeader = CONF.CONFIG.get('Chat')['ChatHeader'];
    if (type != "chat"){return;}
    if (sendmsg.substring(0, 2) == `{"`){return;}
    if (chatHeader != '' && sendmsg.substring(0, 1) != chatHeader){
        return;
    }
    if (sendmsg.substring(0, 1) == chatHeader){
        sendmsg = sendmsg.slice(1);
    }

    // 广播聊天消息
    WSS.clientsManager.forEach(client => {
        client.sendJson(
            new Response(Response.MODE.TEXT)
            .setMsg(`${utils.msgHeader(sender, thisClient.name)} §a${sendmsg}`)
            .setRequestId(CONSTANTS.REQUEST_ID.PLAYERCHAT)
            .setData({
                sender: sender,
                msg: sendmsg,
                serverName: thisClient.name,
                time: req.body.time,
            })
            .setSourceId(thisClient.id)
            .setSourceBdsUuid(thisClient?.bds?.uuid)
            .setSourceBdsServerName(thisClient?.name)
        );
    }, [thisClient.id]);
    
    // WS协调服务端 控制台聊天显示
    if (CONF.CONFIG.get('Chat')['ConsoleDisplay'] == true){
        WSS.logger.info(`[${thisClient.name}]<${sender}> ${sendmsg}` );
    }

    // 聊天记录到日志
    if (CONF.CONFIG.get('Chat')['ChatLog'] == true){
        WSS.logger.write(`[${thisClient.name}]<${sender}> ${sendmsg}`);
    }
    
    // 本地事件
    WSS.api.listener.emit(CONSTANTS.EVENT.PLAYER_CHAT, new LocalEvent()
        .setSourceId(thisClient.id)
        .setSourceBdsUuid(thisClient.bds.uuid)
        .setSourceBdsServerName(thisClient.name)
        .setStatusCode(0)
        .setStatusMessage(``)
        .setData({
            sender: sender,
            msg: sendmsg,
            serverName: thisClient.name,
            time: req.body.time,
        }).json
    );
    return;
});         